﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Chapter21.Models.EventSamples
{
    using System.Threading;
    using System.Diagnostics;

    public class Runner
    {
        private ManualResetEventSlim manualResetEventSlim;
        private ManualResetEventSlim manualResetEventSlimMain;

        public ManualResetEventSlim ManualResetEventSlimMain
        {
            get { return manualResetEventSlimMain; }
            set { manualResetEventSlimMain = value; }
        }

        public ManualResetEventSlim ManualResetEventSlim
        {
            get { return manualResetEventSlim; }
            set { manualResetEventSlim = value; }
        }
        private CountdownEvent countdownEvent;

        public Runner(ManualResetEventSlim manualResetEventSlim, ManualResetEventSlim manualResetEventSlimMain)
        {
            this.manualResetEventSlim = manualResetEventSlim;
            this.manualResetEventSlimMain = manualResetEventSlimMain;
        }
        public Runner(CountdownEvent countdownEvent)
        {
            this.countdownEvent = countdownEvent;
        }

        public void Run()
        {
            var r = new Random();
            Console.WriteLine("运动员 {0} 站在起跑线", Task.CurrentId);
            manualResetEventSlim.Wait();
            var s = Stopwatch.StartNew();
            Console.WriteLine("运动员 {0} 开始起跑", Task.CurrentId);
            Thread.Sleep(r.Next(10000));
            Console.WriteLine("运动员 {0} 到达终点 时间 {1}", Task.CurrentId, s.Elapsed);
            s.Stop();
            manualResetEventSlim.Reset();
            Console.WriteLine("运动员 {0} 等待第2轮开始", Task.CurrentId);
            manualResetEventSlimMain.Set();
            manualResetEventSlim.Wait();
            s.Start();
            Console.WriteLine("运动员 {0} 开始起跑", Task.CurrentId);
            Thread.Sleep(r.Next(10000));
            Console.WriteLine("运动员 {0} 到达终点 时间 {1}", Task.CurrentId, s.Elapsed);
            s.Stop();
            manualResetEventSlim.Reset();
            Console.WriteLine("运动员 {0} 等待第3轮开始", Task.CurrentId);
            manualResetEventSlim.Wait();
            s.Start();
            Console.WriteLine("运动员 {0} 开始起跑", Task.CurrentId);
            Thread.Sleep(r.Next(10000));
            Console.WriteLine("运动员 {0} 到达终点时间 {1}", Task.CurrentId, s.Elapsed);
            manualResetEventSlim.Reset();
            Console.WriteLine("运动员 {0} 全程结束", Task.CurrentId);
        }
    }
}
